#!/usr/bin/python3.6
from datetime import datetime
import urllib.request
import json
import ssl
import sys


# 创建一个不验证 SSL 证书的上下文
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

def gettoken(corpid, corpsecret):
    gettoken_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}'
    print(gettoken_url)



    try:
        # 使用自定义的 SSL 上下文发送请求
        with urllib.request.urlopen(gettoken_url, context=context) as token_response:
            token_data = token_response.read().decode('utf-8')
    except urllib.error.HTTPError as e:
        print(e.code)
        error_response = e.read().decode("utf8")
        print(error_response)
        sys.exit()

    token_json = json.loads(token_data)
    token = token_json.get('access_token')
    return token

def senddata(access_token, subject, content):
    send_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
    send_values = {
        "touser": "qingqingxiaocao",
        "toparty": "25",
        "msgtype": "text",
        "agentid": "4", #4
        "text": {
            "content": subject + '\n' + content
        },
        "safe": "0"
    }
    send_data = json.dumps(send_values, ensure_ascii=False).encode('utf-8')
    print(send_data)
    send_request = urllib.request.Request(send_url, data=send_data, headers={'Content-Type': 'application/json'})

    # 使用自定义的 SSL 上下文发送请求
    try:
        with urllib.request.urlopen(send_request, context=context) as response:
            response_data = response.read().decode('utf-8')
            print(json.loads(response_data))
    except urllib.error.HTTPError as e:
        print(e.code)
        error_response = e.read().decode("utf8")
        print(error_response)

#定义消息接受的应用的秘钥
def dosenddata(subject, content,important):
    corpid = 'wx4574fbc7e8b6a3a5'  # CorpID是企业号的标识
    corpsecret = 'ulLIM-xruWUtYnA5ZbGnK2n8j2_Rau0RiHo4PnnVVgs'  # corpsecretSecret是管理组凭证密钥
    access_token = gettoken(corpid, corpsecret)
    if important == 1:
        subject = '①✨通消,留意 ' + subject #通知类消息,需留意
    elif important == 2:
        subject = '②🌟重要,需警惕 ' + subject #重要类消息,需警惕
    elif important == 3:
        subject = '③❤❄★★★紧急,须处理 ' + subject+"💫🌠" #幅度已够,需出手 需处理
    elif important == 4:
        subject = '④😈💀🧙★★★紧急‍'+ subject+"❗💣" #及其精准的消息

    senddata(access_token, subject, content)